const url = require("url").URL;
class Router{
	constructor(req, config){
		const req_url = new url(req.url, `http://{req.headers.host}`);
		let path = req_url.pathname;
		if (path === "/") {
			this.router = config.router.default;
			config.dir.set("appname",config.apps.default);
		} else {
			let path_arr = path.split("/");
				path_arr.shift();
			this.gets = {};
			console.log(path_arr);
			if (config.apps.list.hasOwnProperty(path_arr[0])) {
				config.dir.set("appname",path_arr[0]);
				path_arr.shift();
			} else {
				config.dir.set("appname",config.apps.default);
			}
			if (path_arr.length >= 3) {
				this.router = {
					module: path_arr[0],
					controll: path_arr[1],
					action: path_arr[2]
				}
				let k = false;
				for (let i=3; i<path_arr.length; i++) {
					if (!k) {
						k = path_arr[i];
						this.gets[k] = "";
					} else {
						this.gets[k] = path_arr[i];
						k = false;
					}
				}
			} else if(path_arr.length === 2) {
				this.router = {
					module: path_arr[0],
					controll: path_arr[1],
					action: "index"
				}
			} else {
				this.router = {
					module: "error",
					controll: "notfound",
					action: "index"
				}
			}
		}

	}
	get(key){
		if (arguments.length === 2) {
			this.gets[arguments[0]] = arguments[1];
		} else {
			return this.gets.hasOwnProperty(key) ? this.gets[key] : false;
		}
	}
	post(key){
		if (arguments.length === 2) {
			this.gets[arguments[0]] = arguments[1];
		} else {
			return this.gets.hasOwnProperty(key) ? this.gets[key] : false;
		}
	}
	getRouter(){
		return this.router;
	}
}
module.exports = {
	init:function(req, config){
		return new Router(req, config);
	}
}